<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/" id="form" method="post">
        名称: <input type="text" name="username"/> <br/>
        密码: <input type="password" name="password"/> <br/>
        手机：<input type="text" name="mobile"/> <br>
        <button>提交</button>
    </form>
    <script>
        (function () {
            var strategies = {
                inNonEmpty:function (value,errorMsg) {
                    if(value==='') return errorMsg;
                },
                minLength:function (value, length, errorMsg) {
                    console.log(length);
                    if(value.length<length) return errorMsg;
                },
                isMobile:function (value, errorMsg) {
                    if(!/(^1[3|5|8][0-9]{9}$)/.test(value)) return errorMsg;
                }
            };



            var Validator = function () {
                this.cache = [];
            };
            Validator.prototype.add = function (dom, rules) {
                var self = this;
                for (var i= 0;i<rules.length ;i++){
                    (function (rule) {
                        var strategyArg = rule.strategy.split(':');
                        var errorMsg = rule.errorMsg;
                        self.cache.push(function () {
                            var strategy = strategyArg.shift();
                            strategyArg.unshift(dom.value);
                            strategyArg.push(errorMsg);
                            return strategies[strategy].apply(dom,strategyArg);
                        })
                    })(rules[i]);
                }

            };

            Validator.prototype.start = function () {
                for(var i=0,validataFunc;validataFunc = this.cache[i++];){
                    var msg = validataFunc();
                    if(msg) return msg
                }
            };

            window.Validator =Validator;

        })();

        var form = document.getElementById('form');

        var validataFunc = function () {

            var validator = new Validator();
            validator.add(form.username,[{
                strategy:'inNonEmpty',
                errorMsg:'名称不能为空'
            },{
                strategy:'minLength:6',
                errorMsg:'名称长度不能小于6位'
            }]);

            validator.add(form.password,[{
                strategy:'minLength:6',
                errorMsg:'密码长度不能少于6位'
            }]);

            validator.add(form.mobile,[{
                strategy:'isMobile',
                errorMsg:'手机格式不正确'
            }]);

            var errorMsg = validator.start();
            return errorMsg;
        }

        form.onsubmit = function () {
            var errorMsg = validataFunc();
            if(errorMsg) {
                alert(errorMsg);
                return false;
            }
        }



    </script>
</body>
</html>